package com.star.controller.user;

import com.star.constant.StatusConstant;
import com.star.entity.Dish;
import com.star.result.Result;
import com.star.service.DishService;
import com.star.vo.DishItemVO;
import com.star.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags ="C端菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate<String, List<DishVO>> redisTemplate;

    /**
     * 根据查询菜品和对应的口味数据列表
     * @param businessId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long businessId){
        log.info("根据商家id查询菜品{}", businessId);
        // 构造redis中的key
        String key = "dish_" + businessId;

        // 判断redis中是否存在菜品数据
        List<DishVO> dishVOList;
        dishVOList = redisTemplate.opsForValue().get(key);

        // 存在
        if(dishVOList != null && !dishVOList.isEmpty()){
            return Result.success(dishVOList);
        }

        // 不存在，查询数据库，并把数据注入redis
        Dish dish = new Dish();
        dish.setBusinessId(businessId);
        dish.setStatus(StatusConstant.ENABLE);

        dishVOList = dishService.getByDishWithFlavors(dish);

        redisTemplate.opsForValue().set(key, dishVOList);
        return Result.success(dishVOList);
    }

    /**
     * 根据菜品id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据套餐id查询包含的菜品")
    public Result<DishVO> getDishListById(@PathVariable Long id){
        log.info("根据套餐id查询包含的菜品{}", id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }
}
